package com.teen9g.infoplatformserver.HttpEntity;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class DeepseekClient {
    @Value("${deepseek.api.key}")
    private String apiKey;

    @Value("${deepseek.api.url}")
    private String apiUrl;

    public String callDeepSeek(String prompt) throws IOException {
        String endpoint = apiUrl + "/completions";

        // 构建请求体 - 使用JSON转义处理特殊字符
        String requestBody = String.format("{\"model\": \"deepseek-chat\", \"prompt\": \"%s\", \"max_tokens\": 300}",
                prompt.replace("\"", "\\\"")); // 处理双引号

        // 创建 HTTP 请求
        HttpPost httpPost = new HttpPost(endpoint);
        httpPost.setHeader("Content-Type", "application/json; charset=UTF-8"); // 添加charset
        httpPost.setHeader("Authorization", "Bearer " + apiKey);
        // 使用UTF-8编码创建StringEntity
        httpPost.setEntity(new StringEntity(requestBody, StandardCharsets.UTF_8));

        // 发送请求并获取响应
        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(httpPost)) {
            HttpEntity entity = response.getEntity();
            // 确保使用UTF-8解码响应
            return EntityUtils.toString(entity, StandardCharsets.UTF_8);
        }
    }
}